package org.ymjava.medical.admin.web;

import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.*;
import org.ymjava.medical.admin.annotation.LoginAdmin;
import org.ymjava.medical.admin.constant.PermType;
import org.ymjava.medical.core.util.ResponseUtil;
import org.ymjava.medical.db.AllPackage.biz.SysPermBiz;
import org.ymjava.medical.db.AllPackage.entity.SysPerm;
import org.ymjava.medical.db.AllPackage.rest.BaseController;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/admin/perm")
public class SysPermController extends BaseController<SysPermBiz,SysPerm> {

	@GetMapping("/list")
	public Object getlist(@LoginAdmin Integer adminId){
		if(adminId == null){
			return ResponseUtil.unlogin();
		}
		String oper = "list menu,button,api permissions";
		List<SysPerm> list =baseBiz.getList(PermType.MENU);
		if (list.isEmpty()){
			return ResponseUtil.ok(oper);
		}else{
			Map<Integer, List<SysPerm>> permMap = list.stream().collect(Collectors.groupingBy(SysPerm::getPtype));
			return ResponseUtil.ok(permMap);
		}
	}

	@PostMapping("/menu")
	public Object synMenuPermission (@RequestBody String body){
		String oper = "sync menu permission";
		List<SysPerm> notSyncedPerms = JSON.parseArray(body, SysPerm.class);
		if(!notSyncedPerms.isEmpty()){
			baseBiz.deleteByptype(PermType.MENU);
			baseBiz.saveOrUpdate(notSyncedPerms);
		}
		return ResponseUtil.ok(oper);
	}
}